 import { 
     accountLoginRequest,
     requestUserInfoById,
     requestUserMenusByRoleId 
} 
 from '@/service/login/login'
 import localCache from '@/utils/cache'
 import router from '@/router'
 import{mapMenusToRoutes,mapMenusToPermissions} from '@/utils/map-menus'
const loginModule={
    namespaced:true,
    state(){
     return {
         token:'',
         userInfo:{},
         userMenus:[],
         permissions:[]
      }
    },
    mutations:{
        changeToken(state,token){
           state.token=token
        },
        changeUserInfo(state,userInfo){
             state.userInfo=userInfo
        },
        changeUserMenus(state,userMenus){
            state.userMenus=userMenus
         const routes=mapMenusToRoutes(userMenus)

        //  注册所有的路由
         routes.forEach((route)=>{
            router.addRoute('main',route)
         })

        //  获取所有按钮的用户权限
        const permissions=mapMenusToPermissions(userMenus)
        state.permissions=permissions
        
        }
    },
    
    actions:{

     async accountloginAction({commit},payload:any){

               // 1 实现登录逻辑  
                const loginResult:any= await accountLoginRequest(payload)
                const {id,token }=loginResult.data
                commit('changeToken',token)
                localCache.setCache('token',token)
                
                //2 请求用户信息
                const UserInfoResult =await requestUserInfoById(id)
                // console.log(UserInfoResult);
                const userInfo= UserInfoResult.data;
                commit('changeUserInfo',userInfo)
                 // 也要缓存到本地存储里
                 localCache.setCache('userInfo',userInfo)


                //  3请求用户菜单
                const userMenusResult= await requestUserMenusByRoleId(userInfo.role.id)
                const userMenus=userMenusResult.data
                // console.log(userMenus);
                commit('changeUserMenus',userMenus)
                localCache.setCache('userMenus',userMenus)
                // 4 调到首页
                router.push('/main')
                
       },

    // 如果进入main首页  刷新 防止本地数据丢失
       loadLocalLogin({commit}){
           const token=localCache.getCache('token')
           if(token){
               commit('changeToken',token)
           }
           const userInfo=localCache.getCache('userInfo')
            if(userInfo){
                commit('changeUserInfo',userInfo)
            }
            const userMenus=localCache.getCache('userMenus')
            if(userMenus){
                commit('changeUserMenus',userMenus)
            }
           
       }

    }
}




export default loginModule